import React, {useState, useEffect} from 'react';

import {
    NavBar,
    Icon,
    List,
    ActionSheet,
    Checkbox,
    TextareaItem,
    Result,
    Radio,
    Popover,
    Carousel,
    Toast,
    Modal,
    Button
} from 'antd-mobile';

import {createForm} from 'rc-form'

import {sexList, R, VOID} from '@/assets/js/dict.js'

import {GetQueryTest, postCommitTest, postSaveTest} from '@/api/tutor/evaluation.js'

import {GetTutorActionDetails} from "@/api/login"

import './evaluation.scss';
import nodata from "@/assets/svg/nodata.svg"


const confirm = Modal.alert;
const Item = List.Item;

const myImg = (src, key) => <img src={src} key={key} className="spe am-icon am-icon-md" alt=""/>;

let Evaluation = (props) => {
    const [questionList, setQuestionList] = useState([{
        checked_answers: null,
        constraint_terms: "{}",
        content: "",
        create_time: null,
        id: "",
        right_answers: "",
        seq: null,
        tutor_id: "",
        update_time: null,
    }])
    const [selectBoxVisible, SetSelectBoxVisible] = useState(false); // 选择题目框的显隐
    const [slideIndex, SetSlideIndex] = useState(0); // 手动设置当前显示的索引 
    const [evaluationVisible, SetEvaluationVisible] = useState(true); // 答题前的提醒 

    // const [MULTIPLEArr, SetMULTIPLEArr] = useState([]); // 多选  

    let [userInfo, setUserInfo] = useState(() => JSON.parse(sessionStorage.getItem('userInfo')));
    let [flush, setFlush] = useState(0);


    function doFlush() {
        setFlush(new Date().getTime())
    }

    // 获取家教的测评内容
    function axiosGetQueryTest() {
        let postData = {
            id: userInfo.id,
        }
        GetQueryTest(postData).then(res => {
            if (res.code == "000000") {
                setQuestionList(res.responseData)
            }
        })
            .catch((err) => {
                console.log('err ----->>>', err)
            })
    }

    // 标题右侧的内容
    function rightContentFn() {
        let rightContentItemArr = [];
        questionList.map((item, index) => {
            rightContentItemArr.push(
                (<Popover.Item key={index}>{item.seq}</Popover.Item>)
            )
        });
        return [rightContentItemArr]
    }

    /**
     * 更新sessionStorage中的用户信息
     */
    function updateUserInfoCache() {
        GetTutorActionDetails({tutor_id: userInfo.id}).then(res => {
            if (R.isSuccess(res)) {
                let data = R.getData(res);
                let info = userInfo;
                info.pass_test = data.pass_test;
                sessionStorage.setItem("user", JSON.stringify(info));
                setUserInfo(info);
            }
        }).catch(err => {

        })
    }

    /**
     * 问题选择
     * @param {Object} val // 选中问题的对象
     * @param {number} index // 选中问题的下标
     * @param {string} optionVal // 选中的值
     */
    var MULTIPLEStr = '';

    function handleOptionBtn(val, index, optionVal) {
        if (index > -1) {
            if (val.type == 'SINGLE') {
                val.checked_answers = optionVal;
                setQuestionList([...questionList]);

                //多选、单选翻页行为不一致，可能会令人迷惑
                // SetSlideIndex(index + 1); // 选中后下一页
            } else if (val.type == 'MULTIPLE') {
                // MULTIPLEArr.push(val.checked_answers.split(''))
                MULTIPLEStr += optionVal
                val.checked_answers = MULTIPLEStr;
            } else if (val.type == 'WRITE') {
                val.checked_answers = optionVal;
            }
        }
    }

    /**
     * 提交测评
     */
    function handleSubmit() {
        let postData = {};
        postData = questionList;
        postCommitTest(postData).then(res => {
            console.log('res  =====>>>', res);
            let code = res.code;
            if (code === R.success) {
                userInfo.pass_test = true;
                setUserInfo(userInfo);
                sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
                doFlush();
                confirm('提示', res.message, [
                    {text: '返回主页', onPress: () => props.history.push({pathname: "/mainTutor"})},
                    {
                        text: '去创建简历', onPress: () => {
                            sessionStorage.removeItem("resume_id");
                            props.history.push({
                                pathname: '/biographicalNotes'
                            });
                        }
                    }])

            } else {
                if (code === R.fail) {
                    // Toast.fail(res.message ? res.message : "测评未通过", 5, VOID, true);
                    confirm('提示', res.message ? res.message : "测评未通过")
                } else {
                    Toast.offline("操作失败：" + res.message ? res.message : '', 5, VOID, true);
                }
            }
        });
    }

    /**
     * 保存测评
     */
    function handleSave() {
        let postData = {};
        postData = questionList;

        postSaveTest(postData).then(res => {
            if (R.isSuccess(res)) {
                Toast.success("保存成功", 2, VOID, false);
            }
        })
            .catch(err => {
                console.log('err  =====>>>', err)
            })
    }

    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let wrapProps;
    if (isIPhone) {
        wrapProps = {
            onTouchStart: e => e.preventDefault(),
        };
    }

    //点击唤起操作栏
    // function showActionSheet () {
    //     if (userInfo.pass_test) {
    //         ActionSheet.showActionSheetWithOptions({
    //             title: '操作栏',
    //             options: ['关闭'],
    //             maskClosable: true,
    //             'data-seed': 'logId',
    //             wrapProps,
    //         },
    //             (buttonIndex) => {
    //             });

    //     } else {
    //         ActionSheet.showActionSheetWithOptions({
    //             options: ['保存进度', '完成答题', '学习资料', '关闭'],
    //             maskClosable: true,
    //             'data-seed': 'logId',
    //             wrapProps,
    //         },
    //             (buttonIndex) => {
    //                 switch (buttonIndex) {
    //                     case 0:
    //                         handleSave();
    //                         break;
    //                     case 1:
    //                         handleSubmit();
    //                         break;
    //                     case 2:
    //                         props.history.push("/materialsDetails");
    //                         break;
    //                     default:
    //                         break;
    //                 }
    //             });
    //     }

    // }

    // 单选， 多选， 填空
    let handleType = (item, index) => {
        if (item.type == 'SINGLE') {
            return (
                Object.keys(JSON.parse(item.constraint_terms)).map((i, k) => {
                    return (
                        <Radio.RadioItem key={`optionBtn-${k}`} checked={item.checked_answers == i}
                                         onChange={() => handleOptionBtn(item, index, i)}
                        >
                            {i}<List.Item.Brief>{JSON.parse(item.constraint_terms)[i]}</List.Item.Brief>
                        </Radio.RadioItem>
                    )
                })
            )
        } else if (item.type == 'MULTIPLE') {
            return (
                Object.keys(JSON.parse(item.constraint_terms)).map((i, k) => {
                    return (
                        // checked={}
                        <Checkbox.CheckboxItem
                            defaultChecked={item.checked_answers != null && ((item.checked_answers).indexOf(i) !== -1)}
                            key={`optionBtn-${k}`} onChange={() => handleOptionBtn(item, index, i)}
                        >
                            {i}<List.Item.Brief>{JSON.parse(item.constraint_terms)[i]}</List.Item.Brief>
                        </Checkbox.CheckboxItem>
                    )
                })
            )
        } else if (item.type == 'WRITE') {
            return (
                <div>
                    <TextareaItem
                        onChange={(text) => handleOptionBtn(item, index, text)}
                        placeholder="请填写"
                        data-seed="logId"
                        autoHeight
                        defaultValue={item.checked_answers}
                    />
                </div>
            )
        }
    };

    function back() {
        props.history.push("/mainTutor");
    }


    // 把 useEffect Hook 看做 componentDidMount，componentDidUpdate 和 componentWillUnmount 这三个函数的组合
    useEffect(() => {
        axiosGetQueryTest()
    }, [flush]);

    if (userInfo.pass_test) {
        return (<div className="evaluation">
            <div className="page-title  evaluation-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left"/>}
                    onLeftClick={back}
                    // rightContent={
                    //     <div style={{ display: questionList.length ? 'block' : 'none' }}>
                    //         <span onClick={showActionSheet}>操作</span>
                    //     </div>
                    // }
                >
                    测评
                </NavBar>
            </div>
            <div className="page-content evaluation-content">
                <div className="evaluation-content-piece">
                    <div className="form-box">
                        <Result
                            buttonText={"返回主页"}
                            img={myImg(nodata, "none")}
                            title=""
                            message="恭喜，您已经通过测评！"
                            buttonType="primary"
                            onButtonClick={back}
                        />
                    </div>
                </div>
            </div>
        </div>)
    } else {
        return (
            <div className="evaluation">
                <div className="page-title  evaluation-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left"/>}
                        onLeftClick={back}
                        // rightContent={
                        //     <div style={{ display: questionList.length ? 'block' : 'none' }}>
                        //         <span onClick={showActionSheet}>操作</span>
                        //     </div>
                        // }
                    >
                        测评
                    </NavBar>

                </div>

                <div className="page-content evaluation-content">
                    <div className="evaluation-content-piece">

                        {
                            !questionList.length ?

                                <div className="form-box">
                                    <Result
                                        buttonText={"返回主页"}
                                        img={myImg(nodata, "none")}
                                        title=""
                                        message="暂无数据"
                                        buttonType="primary"
                                        onButtonClick={back}
                                    />
                                </div>

                                :

                                <div>
                                    <div className="form-box">
                                        <Carousel
                                            autoplay={false}
                                            selectedIndex={slideIndex}
                                            afterChange={index => {
                                                SetSlideIndex(index)
                                            }}
                                        >

                                            {questionList.map((item, index) => {
                                                return (
                                                    <div key={`Carousel-${index}`}>
                                                        <h3><span className="circular">{item.seq}</span> {item.content}
                                                        </h3>
                                                        <div className="option-btn">
                                                            <List key={`optionList-${index}`}>
                                                                {

                                                                    handleType(item, index)
                                                                }
                                                            </List>
                                                            <Button style={{
                                                                marginTop: '20%',
                                                                display: questionList.length - 1 == index ? 'block' : 'none'
                                                            }} type="primary" onClick={() => {
                                                                handleSubmit()
                                                            }}>完成答题</Button>
                                                        </div>
                                                    </div>
                                                )
                                            })}
                                        </Carousel>
                                    </div>
                                    <span className="select-block" onClick={
                                        () => {
                                            SetSelectBoxVisible(!selectBoxVisible)
                                        }
                                    }
                                    />
                                </div>
                        }


                        {/* 题目选择提示框 */}
                        <div className={selectBoxVisible ? "select-box show" : "select-box hide"}>

                            <div className="option-box">
                                {selectBoxVisible}
                                <div className="option-box-tit">
                                    请选择题目
                                </div>
                                <div className="option-box-body">
                                    {
                                        questionList.map((item, index) => {
                                            return (
                                                <span key={`Carousel-tips-${index}`}
                                                      className={index === slideIndex ? 'active' : ''} onClick={() => {
                                                    SetSlideIndex(index);
                                                    SetSelectBoxVisible(!selectBoxVisible)
                                                }}
                                                >{item.seq}</span>
                                            )
                                        })
                                    }
                                </div>


                            </div>
                            <div className="select-box-bg"/>
                        </div>

                    </div>
                </div>

                <Modal
                    popup
                    visible={evaluationVisible}
                    animationType="slide-up"
                    onClose={() => {
                        SetEvaluationVisible(false)
                    }}
                    afterClose={() => {
                    }}
                >
                    <div className="notes-tips">
                        <h3>
                            注意
                        </h3>
                        <div className="notes-tips-content">
                            <p>测前请认真阅读“学习资料”，100%正确才算合格，您只有3次测试机会</p>
                        </div>
                        <div className="notes-tips-footer">
                            <Button type="primary" onClick={() => {
                                SetEvaluationVisible(false)
                            }}>知道了</Button>
                        </div>
                    </div>
                </Modal>
            </div>
        );
    }


}

Evaluation = createForm()(Evaluation);

export default Evaluation;